package com.kgcx.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.SMS;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 极光推送
 *
 * @author Administrator
 */
@Component
public class AuroraPush {
    public static final String PLATFORM_ANDROID = "android";
    public static final String PLATFORM_IOS = "ios";
    public static final String PLATFORM_ALL = "all";

    public static final String MSG_ORDER_SCHEDULED_SUCCESS = "OrderScheduledSuccess"; // 给司机的派单成功消息
    public static final String MSG_CHANGE_DRIVER_SUCCESS = "ChangeDriverSuccess"; // 给司机的改派成功消息（旧司机，不是新司机）
    public static final String MSG_DRIVER_INVITE_PARK = "DriverInvitePark"; // 给司机的邀请入栈消息
    public static final String MSG_DRIVER_UPDATE_STATE = "DriverUpdateState"; // 给司机的邀请入栈消息

    private static final Logger LOG = LoggerFactory.getLogger(AuroraPush.class);

    // 司机端
    private static String DRIVER_APPKEY = "8010fb642ee7fe86edc48843"; // 测试版为97590e4cce38fd220d362d92
    private static String DRIVER_SECRET = "6deee4d99fff7f5d0f810f3c"; // 测试版为76e56cf81774b2c49f9df8a6

    // 乘客端
    private static String USER_APPKEY = "0147074a30363340b4583639"; // 测试版为91a3a915bc7b6712edf146fd
    private static String USER_SECRET = "17bcf27ed86094aa9425d28c"; // 测试版为c557859fcc0cbfdd91edd69b

    @Value("${kgcx.jpush.driver.appkey:97590e4cce38fd220d362d92}")
    public void setDriverAppkey(String driverAppkey) {
        DRIVER_APPKEY = driverAppkey;
    }

    @Value("${kgcx.jpush.driver.secret:76e56cf81774b2c49f9df8a6}")
    public void setDriverSecret(String driverSecret) {
        DRIVER_SECRET = driverSecret;
    }

    @Value("${kgcx.jpush.user.appkey:91a3a915bc7b6712edf146fd}")
    public void setUserAppkey(String userAppkey) {
        USER_APPKEY = userAppkey;
    }

    @Value("${kgcx.jpush.user.secret:c557859fcc0cbfdd91edd69b}")
    public void setUserSecret(String userSecret) {
        USER_SECRET = userSecret;
    }

    public static void pushAll(String msg) {
        JPushClient jpushClient = new JPushClient(DRIVER_SECRET, DRIVER_APPKEY, null, ClientConfig.getInstance());

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_all_alert(msg);

        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println("pushAll=" + result);
            // LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            e.printStackTrace();
            // LOG.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            // LOG.error("Should review the error, and fix the request", e);
            // LOG.info("HTTP Status: " + e.getStatus());
            // LOG.info("Error Code: " + e.getErrorCode());
            // LOG.info("Error Message: " + e.getErrorMessage());
            e.printStackTrace();
        }
    }

    public static void pushTargetForDriver(String where, String msg) {
        JPushClient jpushClient = new JPushClient(DRIVER_SECRET, DRIVER_APPKEY, null, ClientConfig.getInstance());
        System.out.println(msg);
        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_alias_alert(where, msg);

        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println(result);
            // LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            e.printStackTrace();
            // Connection error, should retry later
            // LOG.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            e.printStackTrace();
            // Should review the error, and fix the request
            // LOG.error("Should review the error, and fix the request", e);
            // LOG.info("HTTP Status: " + e.getStatus());
            // LOG.info("Error Code: " + e.getErrorCode());
            // LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void pushTargetForUser(String where, String msg) {
        JPushClient jpushClient = new JPushClient(USER_SECRET, USER_APPKEY, null, ClientConfig.getInstance());
        System.out.println(msg);
        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_alias_alert(where, msg);

        try {
            PushResult result = jpushClient.sendPush(payload);
            // jpushClient.
            System.out.println(result);
            // LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            e.printStackTrace();
            // Connection error, should retry later
            // LOG.error("Connection error, should retry later", e);
        } catch (APIRequestException e) {
            e.printStackTrace();
            // Should review the error, and fix the request
            // LOG.error("Should review the error, and fix the request", e);
            // LOG.info("HTTP Status: " + e.getStatus());
            // LOG.info("Error Code: " + e.getErrorCode());
            // LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    // 消息
    public static void pushTargetMsgForDriver(String title, String content, String alias, String platform) {
        LOG.info(String.format("推送%s消息：alias=%s，title=%s，content=%s", platform, alias, title, content));

        JPushClient jpushClient = new JPushClient(DRIVER_SECRET, DRIVER_APPKEY, null, ClientConfig.getInstance());
        if (PLATFORM_IOS.equals(platform)) {
            sendIosMessageWithAlias(jpushClient, title, content, alias);
        } else if (PLATFORM_ANDROID.endsWith(platform)) {
            sendAndroidMessageWithAlias(jpushClient, title, content, alias);
        } else {
            sendAndroidMessageWithAlias(jpushClient, title, content, alias);
            sendIosMessageWithAlias(jpushClient, title, content, alias);
        }
    }

    private static void sendAndroidMessageWithAlias(JPushClient jpushClient, String title, String content,
            String alias) {
        try {
            jpushClient.sendAndroidMessageWithAlias(title, content, alias);
        } catch (Exception e) {
            LOG.error(String.format("推送Android消息失败！alias=%s，title=%s，content=%s", alias, title, content), e);
        }
    }

    private static void sendIosMessageWithAlias(JPushClient jpushClient, String title, String content, String alias) {
        try {
            jpushClient.sendIosMessageWithAlias(title, content, alias);
        } catch (Exception e) {
            LOG.error(String.format("推送Ios消息失败！alias=%s，title=%s，content=%s", alias, title, content), e);
        }
    }

    // 快捷地构建推送对象：所有平台，所有设备，内容为 ALERT 的通知
    public static PushPayload buildPushObject_all_all_alert(String msg) {
        return PushPayload.alertAll(msg);
    }

    // 所有平台，推送目标是别名为 "alias1"，通知内容为 ALERT
    public static PushPayload buildPushObject_all_alias_alert(String where, String msg) {
        return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(where))
                .setNotification(Notification.alert(msg)).build();
    }

    // 所有平台，推送目标是标签为 "alias1"，通知内容为 ALERT
    public static PushPayload buildPushObject_all_tags_alert(String where, String msg) {
        return PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.tag(where))
                .setNotification(Notification.android(msg, "订单推送", null)).build();
    }
    // 平台是 Android，目标是 tag 为 "tag1" 的设备，内容是 Android 通知 ALERT，并且标题为 TITLE
    /*
     * public static PushPayload buildPushObject_android_tag_alertWithTitle() { return PushPayload.newBuilder()
     * .setPlatform(Platform.android()) .setAudience(Audience.tag("tag1")) .setNotification(Notification.android(ALERT,
     * TITLE, null)) .build(); }
     */
    // 平台是 iOS，推送目标是 "tag1", "tag_all" 的交集，推送内容同时包括通知与消息
    // - 通知信息是 ALERT，角标数字为 5，通知声音为 "happy"，并且附加字段 from = "JPush"；
    // 消息内容是 MSG_CONTENT。通知是 APNs 推送通道的，消息是 JPush 应用内消息通道的。
    // APNs 的推送环境是“生产”（如果不显式设置的话，Library 会默认指定为开发）
    /*
     * public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() { return
     * PushPayload.newBuilder() .setPlatform(Platform.ios()) .setAudience(Audience.tag_and("tag1", "tag_all"))
     * .setNotification(Notification.newBuilder() .addPlatformNotification(IosNotification.newBuilder() .setAlert(ALERT)
     * .setBadge(5) .setSound("happy") .addExtra("from", "JPush") .build()) .build())
     * .setMessage(Message.content(MSG_CONTENT)) .setOptions(Options.newBuilder() .setApnsProduction(true) .build())
     * .build(); }
     */
    // 平台是 Andorid 与 iOS，推送目标是 （"tag1" 与 "tag2" 的并集）交（"alias1" 与 "alias2" 的并集），
    // 推送内容是 - 内容为 MSG_CONTENT 的消息，并且附加字段 from = JPush
    /*
     * public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() { return PushPayload.newBuilder()
     * .setPlatform(Platform.android_ios()) .setAudience(Audience.newBuilder()
     * .addAudienceTarget(AudienceTarget.tag("tag1", "tag2")) .addAudienceTarget(AudienceTarget.alias("alias1",
     * "alias2")) .build()) .setMessage(Message.newBuilder() .setMsgContent(MSG_CONTENT) .addExtra("from", "JPush")
     * .build()) .build(); }
     */

    // 推送内容包含SMS信息
    public static void testSendWithSMS() {
        JPushClient jpushClient = new JPushClient(DRIVER_SECRET, DRIVER_APPKEY);
        try {
            SMS sms = SMS.content("Test SMS", 10);
            PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
            // LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            // LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            // LOG.error("Error response from JPush server. Should review and fix it. ", e);
            // LOG.info("HTTP Status: " + e.getStatus());
            // LOG.info("Error Code: " + e.getErrorCode());
            // LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    /*
     * public static PushPayload buildPushObject_all_all_alert(String ALERT) { return PushPayload.alertAll(ALERT); }
     */
    public static void main(String[] args) {

        // buildPushObject_all_alias_alert("16","测试mq");
        // buildPushObject_all_all_alert("测试mq");
        // pushTarget("16","899999999");
    }
}
